package org.hamster.common.services
{
	import mx.controls.ProgressBar;
	import mx.core.IFlexDisplayObject;
	import mx.core.UIComponent;
	import mx.managers.PopUpManager;
	
	import org.hamster.common.components.LoadingMaskComp;

	public class LoadingMaskService
	{
		private static var _instance:LoadingMaskService;
		
		public static function initInstance(app:UIComponent, loadingMaskClass:Class = null):LoadingMaskService
		{
			if (_instance == null) {
				_instance = new LoadingMaskService();
				_instance.app = app;
				if (loadingMaskClass == null) {
					_instance.loadingMaskClass = LoadingMaskComp;
				} else {
					_instance.loadingMaskClass = loadingMaskClass;
				}
			}
			return _instance;
		}
		
		public static function get instance():LoadingMaskService
		{
			return _instance;
		}
		
		public var loadingMaskClass:Class;
		public var app:UIComponent;
		
		private var _loadingMaskComp:Object;
		private var _count:int = 0;
		
		public function show(text:String):void
		{
			if (_loadingMaskComp && _loadingMaskComp.hasOwnProperty('label')) {
				_loadingMaskComp.label += '\n' + text;
			} else {
				_loadingMaskComp = PopUpManager.createPopUp(app, loadingMaskClass, true);
				PopUpManager.centerPopUp(_loadingMaskComp as IFlexDisplayObject);
				if (_loadingMaskComp.hasOwnProperty('label')) {
					_loadingMaskComp.label = text;
				}
			}
			_count++;
		}
		
		public function setText(text:String):void
		{
			if (_loadingMaskComp && _loadingMaskComp.hasOwnProperty('label')) {
				_loadingMaskComp.label = text;
			}
		}
		
		public function hide():void
		{
			_count--;
			if (_count <= 0) {
				_count = 0;
			}
			
			PopUpManager.removePopUp(_loadingMaskComp as IFlexDisplayObject);
			_loadingMaskComp = null;
		}
	}
}